package cn.com.nes.site.listener;

import cn.com.nes.site.entity.em.UnitEnum;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

public class DataUnitConvert implements Converter<String> {
    @Override
    public Class supportJavaTypeKey() {
        return String.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public String convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                    GlobalConfiguration globalConfiguration) {
        for (UnitEnum unit : UnitEnum.values()) {
            if (unit.getValue().equalsIgnoreCase(cellData.getStringValue())) {
                return unit.toString().replace("_", "-");
            }
        }
        return cellData.getStringValue();
    }

    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty,
                                               GlobalConfiguration globalConfiguration) {
        UnitEnum unit;
        try {
            unit = UnitEnum.valueOf(value.replace("-", "_"));
        } catch (IllegalArgumentException e) {
            return new WriteCellData<>(value);
        }
        return new WriteCellData<>(unit.getValue());
    }

}
